package com.feidian.helper.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.feidian.helper.R;
import com.feidian.helper.adapter.XListViewAdapter;
import com.feidian.helper.bean.Item;
import com.feidian.helper.bean.Table;
import com.feidian.helper.bean.User;
import com.feidian.helper.net.NetManager;
import com.feidian.helper.ui.NewsDetailsAcceptActivity;
//import com.feidian.helper.ui.fragment.SendFragment.RefreshThread;
import com.feidian.helper.ui.view.MyDialog;
import com.feidian.helper.util.Constant;
import com.feidian.helper.util.Utils;

import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

/**
 * 
 * @author lxq or linxingqianglai and WangCheng
 * @category category 用户结单的类
 * 
 */
@SuppressLint("NewApi")
public class AcceptFragment extends Fragment implements OnTouchListener {

	private final int REFRESH_SUCCESS = 0x123;
	private final int REFRESH_FAILURE = 0X124;
	private final int LOAD_SUCCESS = 0x125;
	private final int LOAD_FAILURE = 0X126;
	private final int LOAD_FOR_MORE = 0X127;

	public static TextView accept_tag = null;
	private TextView mTitle;
	private ImageView mBack;
	private ImageView mRight;// 添加功能
	private PullToRefreshListView mRefreshListView = null;
	private XListViewAdapter adapter;
	private static int page = 1;
	public static List<Item> itemList = new ArrayList<Item>();
	public static int pos;
	public static boolean isRefresh = false;
	public static Dialog mDialog = null;
	public static Button mSure = null;
	public static Button mCancel = null;
	public boolean refresh = false;
	public SharedPreferences sp = null;
	// public static boolean is_no_news = true;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REFRESH_SUCCESS:
				page = 2;
				if (itemList != null && (String) msg.obj != null)
					addItems(itemList, (String) msg.obj, 0);
				adapter.notifyDataSetChanged();
				mRefreshListView.onRefreshComplete();
				mRefreshListView.setEnabled(true);
				if (itemList.size() == 0) {
					accept_tag.setVisibility(View.VISIBLE);
					accept_tag.setText("暂时无消息显示");
					// Toast.makeText(getActivity(), "暂时无消息显示",
					// Toast.LENGTH_SHORT).show();
				} else {
					// Toast.makeText(getActivity(), "刷新成功",
					// Toast.LENGTH_SHORT).show();
					accept_tag.setVisibility(View.GONE);
				}
				refresh = false;
				break;
			case REFRESH_FAILURE: {
				mRefreshListView.onRefreshComplete();
				mRefreshListView.setEnabled(true);
			}
				if (itemList.size() == 0) {
					accept_tag.setVisibility(View.VISIBLE);
					accept_tag.setText("暂时无消息显示");
					// Toast.makeText(getActivity(), "暂时无消息更新",
					// Toast.LENGTH_SHORT).show();
				} else {
					accept_tag.setVisibility(View.GONE);
				}
				break;
			case LOAD_SUCCESS:
				page++;
				if (itemList != null && (String) msg.obj != null) {
					addItems(itemList, (String) msg.obj, 1);
				}
				adapter.notifyDataSetChanged();
				mRefreshListView.onRefreshComplete();
				mRefreshListView.setEnabled(true);
				if (itemList.size() == 0) {
					accept_tag.setVisibility(View.VISIBLE);
					Toast.makeText(getActivity(), "暂时无消息更新", Toast.LENGTH_SHORT)
							.show();
				} else {
					accept_tag.setVisibility(View.GONE);
				}
				refresh = false;
				break;
			case LOAD_FAILURE: {
				mRefreshListView.onRefreshComplete();
				mRefreshListView.setEnabled(true);
				if (itemList.size() == 0) {
					accept_tag.setVisibility(View.VISIBLE);
					Toast.makeText(getActivity(), "暂时无消息更新", Toast.LENGTH_SHORT)
							.show();
				} else {
					accept_tag.setVisibility(View.GONE);
				}
			}
			case LOAD_FOR_MORE:{
				onDownPullRefresh();
			}
				break;
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final Context context = this.getActivity();
		sp = getActivity().getSharedPreferences(Table.CommentUserInf, Context.MODE_PRIVATE);
		View view = inflater.inflate(R.layout.accepte_fragment, container,
				false);
		init(view, context);
		if (itemList.size() == 0) {
			accept_tag.setVisibility(View.VISIBLE);
			accept_tag.setText("下拉以刷新");
		} else {
			accept_tag.setVisibility(View.GONE);
		}
		return view;
	}

	private void init(View view, final Context context) {
		/*
		 * 实例化dialog
		 */
		mDialog = new Dialog(getActivity(), R.style.dialog);
		LayoutInflater layoutInflater = getActivity().getLayoutInflater();
		View v = layoutInflater.inflate(R.layout.dialog, null, false);
		TextView delete_dialog_title = (TextView) v
				.findViewById(R.id.dialog_title);
		TextView delete_dialog_content = (TextView) v
				.findViewById(R.id.dialog_content);
		delete_dialog_title.setText("删除提醒");
		delete_dialog_content.setText("是否要删除?");
		mSure = (Button) v.findViewById(R.id.button1);
		mCancel = (Button) v.findViewById(R.id.button2);
		mSure.setText("确认删除");
		mCancel.setText("取消");
		mDialog.setContentView(v);

		mBack = (ImageView) view.findViewById(R.id.back);
		mBack.setVisibility(View.GONE);
		mRight = (ImageView) view.findViewById(R.id.right);
		mRight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// startActivity(new
				// Intent(getActivity(),SearchActivity.class));
			}
		});
		accept_tag = (TextView) view.findViewById(R.id.tag);
		mTitle = (TextView) view.findViewById(R.id.title);
		mTitle.setText(getActivity().getResources().getString(R.string.accept));
		mRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.pull_refresh_list);
		adapter = new XListViewAdapter(getActivity(), itemList);
		mRefreshListView.setMode(Mode.BOTH);
		mRefreshListView
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase refreshView) {
						// TODO Auto-generated method stub
						refresh = true;
						onDownPullRefresh();
					}

					@Override
					public void onPullUpToRefresh(PullToRefreshBase refreshView) {
						// TODO Auto-generated method stub
						onLoadingMore();
					}
				});
		mRefreshListView.setAdapter(adapter);
		mRefreshListView.setOnTouchListener(this);
		/*
		 * 设置点击监听
		 */
		setOnClickListener();
		// onDownPullRefresh();
	}

	@Override
	public boolean onTouch(View v, MotionEvent e) {
		int downY = 0;
		int moveY;
		switch (e.getAction()) {
		case MotionEvent.ACTION_DOWN:
			Log.e("touch", "down");
			downY = (int) e.getRawY();
			return true;
		case MotionEvent.ACTION_MOVE:
			Log.e("touch", "move");
			moveY = (int) e.getRawY();
			if (moveY > downY) {
				accept_tag.setVisibility(View.GONE);
			}
			return false;

		default:
			Log.e("touch", "default");
			return false;
		}

	}

	private void setOnClickListener() {
		// TODO Auto-generated method stub
		if (mRefreshListView != null) {
			mRefreshListView.getRefreshableView().setOnItemClickListener(
					new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							pos = position - 1;
							getActivity().startActivity(
									new Intent(getActivity(),
											NewsDetailsAcceptActivity.class));
						}
					});
			mRefreshListView.getRefreshableView().setOnItemLongClickListener(
					new OnItemLongClickListener() {
						@Override
						public boolean onItemLongClick(AdapterView<?> parent,
								View view, int position, long id) {
							Log.e("LongClick", "...");
							if (sp.getBoolean(/*Table.CommentUserInf*/Table.isLogin, false)) {
								pos = position - 1;
								if(itemList.get(pos).getState().equals("1")){
									Toast.makeText(getActivity(), "求助在处理中不能删除", Toast.LENGTH_LONG).show();
									return true;
								}
								mSure.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {

										String url = "http://115.29.103.105/User/delObject";
										List<NameValuePair> params = new ArrayList<NameValuePair>();
										params.add(new BasicNameValuePair(
												Table.id, itemList.get(pos)
														.getId()));
										UnionThreads deleteThread = new UnionThreads(
												url, params,Constant.DELETE);
										deleteThread.start();
										mDialog.dismiss();
									}
								});
								mCancel.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										mDialog.dismiss();
									}
								});
								mDialog.show();
							} else {
								Toast.makeText(
										AcceptFragment.this.getActivity(),
										"用户未登录", Toast.LENGTH_SHORT).show();
							}
							return true;
						}
					});
		}
	}

	class UnionThreads extends Thread {
		String url;
		List<NameValuePair> params;
        int kind;
		public UnionThreads(String mUrl, List<NameValuePair> mParams,int kind) {
			url = mUrl;
			params = mParams;
			this.kind = kind;
		}

		@Override
		public void run() {
			String context = NetManager.getNetManager().getWebWithPost(url,
					params);
			Log.e("DeleteThread", context);
			switch(kind) {
			case Constant.DELETE:
				if (context == "-1") {

				} else {
					Message msg=mHandler.obtainMessage();
					msg.what=Constant.LOAD_FOR_MORE;
					mHandler.handleMessage(msg);
				}
				break;
			case Constant.REFRESH:
				if (context == null) {
					Log.e("you can't get data ", ".......");

					return;
				} else {
					Log.e("context=", context);
					// f(context);
					Message msg = mHandler.obtainMessage();
					msg.what = Constant.REFRESH_SUCCESS;
					msg.obj = context;
					mHandler.sendMessage(msg);
				}
				break;
			case Constant.LOAD:
				if (context == null) {
					Log.e("you can't get data ", ".......");
				} else {
					Log.e("context=", context);
					Message msg = mHandler.obtainMessage();
					msg.what = Constant.LOAD_SUCCESS;
					msg.obj = context;
					mHandler.sendMessage(msg);
				}
				break;
			}
		}
	}
	/*
	class DeleteThread extends Thread {
		String url;
		List<NameValuePair> params;

		public DeleteThread(String mUrl, List<NameValuePair> mParams) {
			url = mUrl;
			params = mParams;
		}

		@Override
		public void run() {
			String context = NetManager.getNetManager().getWebWithPost(url,
					params);
			Log.e("DeleteThread", context);
			if (context == "-1") {

			} else {
				Message msg=mHandler.obtainMessage();
				msg.what=LOAD_FOR_MORE;
				mHandler.handleMessage(msg);
			}
		}
	}
    */
	public void onDownPullRefresh() {
		accept_tag.setVisibility(View.GONE);
		itemList.clear();
		if (!sp.getBoolean(Table.isLogin, false)) {
			Toast.makeText(getActivity(), "用户未登录", Toast.LENGTH_LONG).show();
			mRefreshListView.onRefreshComplete();
			mRefreshListView.setEnabled(true);
			accept_tag.setVisibility(View.VISIBLE);
			accept_tag.setText("用户未登陆");
			return;
		}
		Log.e("onRefresh", "onRefresh");
		String url = "http://115.29.103.105/User/getRefreshDate";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Table.stuId, User.stuId));
		params.add(new BasicNameValuePair(Table.state, "2"));
		params.add(new BasicNameValuePair(Table.page, "1"));
		UnionThreads refreshThread = new UnionThreads(url, params,Constant.REFRESH);
		refreshThread.start();
	}

	public void onLoadingMore() {
		if (User.name == null || User.password == null
				|| User.password.equals("null")) {
			Toast.makeText(getActivity(), "用户未登录", Toast.LENGTH_LONG).show();
			mRefreshListView.onRefreshComplete();
			mRefreshListView.setEnabled(true);
			return;
		}
		String url = "http://115.29.103.105/User/getRefreshDate";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Table.stuId, User.stuId));
		params.add(new BasicNameValuePair(Table.state, "1"));
		params.add(new BasicNameValuePair(Table.page, page + ""));
		UnionThreads loadThread = new UnionThreads(url, params,Constant.LOAD);
		loadThread.start();
	}
    /*
	class RefreshThread extends Thread {
		private String mUrl;
		private List<NameValuePair> mParams;

		public RefreshThread(String url, List<NameValuePair> params) {
			// TODO Auto-generated constructor stub
			mUrl = url;
			mParams = params;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			String context = NetManager.getNetManager().getWebWithPost(mUrl,
					mParams);
			if (context == null) {
				Log.e("you can't get data ", ".......");

				return;
			} else {
				Log.e("context=", context);
				// f(context);
				Message msg = mHandler.obtainMessage();
				msg.what = REFRESH_SUCCESS;
				msg.obj = context;
				mHandler.sendMessage(msg);
			}

			super.run();
		}
	}
    */
	/*
	class LoadThread extends Thread {
		private String mUrl;
		private List<NameValuePair> mParams;

		public LoadThread(String url, List<NameValuePair> params) {
			// TODO Auto-generated constructor stub
			mUrl = url;
			mParams = params;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			String context = NetManager.getNetManager().getWebWithPost(mUrl,
					mParams);
			if (context == null) {
				Log.e("you can't get data ", ".......");
			} else {
				Log.e("context=", context);
				Message msg = mHandler.obtainMessage();
				msg.what = LOAD_SUCCESS;
				msg.obj = context;
				mHandler.sendMessage(msg);
			}

			super.run();
		}

	}
    */
	/**
	 * 
	 * @param list
	 * @param context
	 *            json数据
	 * @param state
	 *            0表示刷新状态，1表示加载状态
	 */
	void addItems(List<Item> list, String context, int state) {
		JSONArray jsonArray;
		List<Item> tempItems = new ArrayList<Item>();
		try {
			jsonArray = new JSONArray(context);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject j = new JSONObject(jsonArray.getString(i));
				String starTime = j.getString(Table.startTime);
				if (starTime.length() - 2 > 7) {
					starTime = starTime.substring(6, starTime.length() - 2);
					starTime = Utils.getStringTime(starTime);

				}
				String endTime = j.getString(Table.endTime);
				if (endTime.length() - 2 > 7) {
					endTime = endTime.substring(6, endTime.length() - 2);
					endTime = Utils.getStringTime(endTime);
				}
				Item item = new Item(j.getString(Table.stuId),
						j.getString(Table.name), j.getString(Table.id),
						j.getString(Table.title), j.getString(Table.content),
						j.getString(Table.money), starTime, endTime,
						j.getString(Table.starts), j.getString(Table.qq),
						j.getString(Table.phone), j.getString(Table.state),
						j.getString(Table.accepStuId),
						j.getString(Table.accepName));
				tempItems.add(item);
			}
			if (state == 0) {
				list.clear();
				list.addAll(tempItems);
			} else {
				list.addAll(tempItems);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onResume() {
		String accepName; // 接单人姓名
		// TODO Auto-generated method stub
		super.onResume();
		Log.e("onResume()1", "....................");
		if (isRefresh) {
			Log.e("onResume()", "....................");
			onDownPullRefresh();
			isRefresh = false;
		}
		adapter.notifyDataSetChanged();
	}

}